<!DOCTYPE html>
<html>
<head>
    <title>角色授权</title>
    {% include 'system/common/header.html' %}
</head>
<body>
<form class="layui-form layui-form-pane" action="">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item">
            <label class="layui-form-label">数据权限</label>
            <div class="layui-input-block">
                <select name="data_scope" lay-verify="required" lay-filter="data_scope">
                    <option value="0">仅本人数据权限</option>
                    <option value="1">本部门数据权限</option>
                    <option value="2">本部门及以下数据权限</option>
                    <option value="3">自定义数据权限</option>
                    <option value="4">全部数据权限</option>
                </select>
            </div>
        </div>
        
        <!-- 自定义数据权限时的部门选择 -->
        <div class="layui-form-item" id="dept_select_container" style="display: none;">
            <label class="layui-form-label">选择部门</label>
            <div class="layui-input-block">
                <ul id="role-dept" class="dtree" data-id="0"></ul>
                <input type="hidden" name="deptIds" id="deptIds">
            </div>
        </div>
            <div class="layui-form-item">
                <label class="layui-form-label">菜单权限</label>
                <div class="layui-input-block">
                    <ul id="role-power" class="dtree" data-id="0"></ul>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-sm" lay-submit="" lay-filter="power-save">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>
{% include 'system/common/footer.html' %}
<script>
    layui.use(['dtree', 'form', 'jquery'], function () {
        let dtree = layui.dtree
        let form = layui.form
        let $ = layui.jquery

        dtree.render({
            elem: '#role-power',
            method: 'get',
            url: '/system/role/getRolePower/{{id}}',
            dataFormat: 'list',
            checkbar: true,
            skin: 'layui',
            initLevel: '1',
            checkbarType: 'self',
            response: {treeId: 'powerId', parentId: 'parentId', title: 'powerName'},
        })

        // 获取当前角色的数据权限范围并设置下拉框默认值
        $.ajax({
            url: '/system/role/getRoleDetail/{{id}}',
            type: 'get',
            dataType: 'json',
            success: function(res) {
                if (res.success) {
                    // 设置数据权限范围下拉框的值
                    $('select[name="data_scope"]').val(res.data.data_scope);
                    form.render('select'); // 重新渲染表单
                    
                    // 检查是否为自定义数据权限并处理部门选择
                    checkDataScope();
                    
                    // 如果有已选择的部门，初始化部门树
                    if (res.data.data_scope === 3) {
                        // 初始化部门树
                        initDeptTree(res.data.deptIds);
                    }
                }
            }
        });
        
        // 监听数据权限变更
        form.on('select(data_scope)', function(data) {
            checkDataScope();
        });
        
        // 检查数据权限并显示/隐藏部门选择
        function checkDataScope() {
            var dataScope = $('select[name="data_scope"]').val();
            if (dataScope == 3) {
                $('#dept_select_container').show();
                // 如果部门树还未初始化，则初始化
                if ($('#role-dept').find('.dtree-wrapper').length === 0) {
                    initDeptTree('');
                }
            } else {
                $('#dept_select_container').hide();
                $('#deptIds').val('');
            }
        }
        
        // 初始化部门树
        function initDeptTree(selectedDeptIds) {
            // 从部门接口获取部门数据
            $.ajax({
                url: '/system/dept/tree',
                type: 'get',
                dataType: 'json',
                success: function(res) {
                    if (res.status && res.status.code === 200) {
                        // 处理部门数据为dtree格式
                        var deptData = [];
                        // 将已选部门ID字符串转换为数组
                        var selectedDeptIdsArray = selectedDeptIds ? selectedDeptIds.split(',') : [];
                        
                        res.data.forEach(function(dept) {
                            deptData.push({
                                deptId: dept.id,
                                parentId: dept.parent_id,
                                deptName: dept.dept_name, // 使用dept_name字段
                                checkArr: selectedDeptIdsArray.includes(dept.id.toString()) ? "1" : "0"
                            });
                        });
                        
                        // 渲染部门树
                        dtree.render({
                            elem: '#role-dept',
                            data: deptData,
                            dataFormat: 'list',
                            checkbar: true,
                            skin: 'layui',
                            initLevel: '1',
                            checkbarType: 'self',
                            response: {treeId: 'deptId', parentId: 'parentId', title: 'deptName'},
                        });
                        
                        // 监听部门树选择事件
                        dtree.on('node(' + 'role-dept' + ')', function(obj) {
                            updateDeptIds();
                        });
                        
                        // 初始更新部门ID
                        updateDeptIds();
                    }
                }
            });
        }
        
        // 更新部门ID到隐藏字段
        function updateDeptIds() {
            var param = dtree.getCheckbarNodesParam('role-dept');
            var ids = '';
            for (var i = 0; i < param.length; i++) {
                var id = param[i].nodeId;
                ids += id + ',';
            }
            ids = ids.substr(0, ids.length - 1);
            $('#deptIds').val(ids);
        }

        form.on('submit(power-save)', function (data) {
            let param = dtree.getCheckbarNodesParam('role-power')
            let ids = ''
            for (let i = 0; i < param.length; i++) {
                let id = param[i].nodeId
                ids += id + ','
            }
            ids = ids.substr(0, ids.length - 1)
            data.field.roleId = {{id}};
            data.field.powerIds = ids;
            
            // 确保部门ID已更新
            if (data.field.data_scope == 3) {
                updateDeptIds();
                data.field.deptIds = $('#deptIds').val();
            } else {
                data.field.deptIds = '';
            }

            $.ajax({
                url: '/system/role/saveRolePower',
                data: JSON.stringify(data.field),
                dataType: 'json',
                type: 'put',
                contentType: 'application/json',
                success: function (result) {
                    if (result.success) {
                        layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name))
                        })
                    } else {
                        layer.msg(result.msg, {icon: 2, time: 1000})
                    }
                }
            })
            return false
        })

    })
</script>
</body>
</html>